<template>
  <div>
    <div class="g-card">
      <div class="h1-title">在职继承</div>
      <SearchCriteria ref="child" @sendMessage="getMessage"></SearchCriteria>
    </div>
    <div class="g-card">
      <!-- 表格 -->
      <div style="padding: 20px 20px 20px 20px">
        <el-table
          ref="mainTable"
          v-loading="loading"
          :data="tableList"
          style="width: 100%"
          height="415"
          @selection-change="handleSelectionChange"
        >
          <el-table-column width="35" fixed>
            <template slot="header">
              <i class="el-icon-setting" @click="openShowList"></i>
            </template>
          </el-table-column>
          <!-- <el-table-column type="selection" width="45" align="center" fixed>
          </el-table-column> -->
          <el-table-column
            type="index"
            label="序号"
            width="50"
            fixed
            align="center"
          ></el-table-column>
          <el-table-column
            prop="sid"
            label="客户号"
            align="center"
            :min-width="200"
            fixed="left"
          >
            <template slot-scope="scope">
              {{ scope.row.sid || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            align="center"
            :min-width="100"
            fixed
          >
            <template slot-scope="scope">
              {{ scope.row.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="customerId"
            label="获客来源"
            align="center"
            :min-width="200"
            fixed="left"
          >
            <template slot-scope="scope">
              {{ scope.row.customerId || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机"
            align="center"
            width="100"
            fixed="left"
          >
            <template slot-scope="scope">
              {{ scope.row.phone || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="wechatNo"
            label="微信号"
            align="center"
            width="100"
            fixed="left"
          >
            <template slot-scope="scope">
              {{ scope.row.wechatNo || '-' }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="follower"
            label="跟进人"
            align="center"
            width="100"
            fixed="left"
          >
            <template slot-scope="scope">
              {{ scope.row.follower || "-" }}
            </template>
          </el-table-column> -->
          <div v-for="(item, i) in tableLists" :key="i">
            <el-table-column
              width="80"
              :prop="item.prop"
              :label="item.label"
              align="center"
              v-if="item.label == '分配状态'"
            >
              <template slot-scope="scope">
                <el-tag
                  type="success"
                  v-if="scope.row.distributionState === '已分配'"
                >已分配
                </el-tag
                >
                <el-tag
                  type="warning"
                  v-if="scope.row.distributionState === '待分配'"
                >待分配
                </el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              width="120"
              :prop="item.prop"
              :label="item.label"
              align="center"
              v-else-if="item.label == '企微添加状态'"
            >
              <template slot-scope="scope">
                <span
                  class="wecomAdd1"
                  v-if="scope.row.wecomAddState === '已添加'"
                >已添加</span
                >
                <span
                  class="wecomAdd2"
                  v-else-if="scope.row.wecomAddState === '待添加'"
                >待添加</span
                >
                <span
                  class="wecomAdd3"
                  v-else-if="scope.row.wecomAddState === '已删除'"
                >已删除</span
                >
                <span class="wecomAdd3" v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column
              width="80"
              :prop="item.prop"
              :label="item.label"
              align="center"
              v-else-if="item.label == '性别'"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.gender === 0"> 未知 </span>
                <span v-else-if="scope.row.gender === 1"> 男 </span>
                <span v-else-if="scope.row.gender === 2"> 女 </span>
              </template>
            </el-table-column>
            <el-table-column
              :prop="item.prop"
              :label="item.label"
              align="center"
              v-else
              :width="160"
            >
              <template slot-scope="scope">
                {{ scope.row[item.prop] || '-' }}
              </template>
            </el-table-column>
          </div>
          <!--          <el-table-column-->
          <!--            label="创建时间"-->
          <!--            align="center"-->
          <!--            prop="createTime"-->
          <!--            show-overflow-tooltip-->
          <!--            :width="160"-->
          <!--          >-->
          <!--          </el-table-column>-->
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="{ row }">
              <div class="option-span">
                <span v-hasPermi="['job:inherit:extend']" @click="inherit(row)"
                >在职继承</span
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <NormalPagination :currentPage="messages.pageNum" :pageSize="messages.pageSize" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
    </div>
    <!-- 在职继承弹窗 -->
    <el-dialog :title="remark" :visible.sync="modifyVisible" width="30%">
      <span style="font-size: 16px; margin-left: 25px"
      >已选中{{ customerList }}，共计{{ customerNumber }}个客户</span
      >
      <el-form
        :model="modifyForm"
        :rules="rules"
        ref="modifyForm"
        style="margin-top: 15px"
      >
        <el-form-item label="转派员工" prop="reassign" label-width="90px">
          <el-select
            filterable
            v-model="modifyForm.reassign"
            placeholder="请选择转派员工"
            style="width: 70%"
          >
            <el-option
              v-for="item in staffList"
              :key="item.userId"
              :label="item.name"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接替文案" prop="text" label-width="90px">
          <el-input
            type="textarea"
            v-model="modifyForm.text"
            maxlength="100"
            show-word-limit
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-form>
      <span style="font-size: 13px; color: #c3c3c3; margin-left: 25px">
        注：转派前请您与该客户的负责人沟通后操作哦！
      </span>
      <div slot="footer">
        <el-button @click="cancelModify">取 消</el-button>
        <el-button type="primary" @click="saveModify" :loading="saveLoading"
        >确认
        </el-button
        >
      </div>
    </el-dialog>
    <!-- 选择展示数据弹窗 -->
    <el-dialog title="选择需要展示的数据项" :visible.sync="dialogFormVisible">
      <showData @sendDataList="getDataList" ref="showDataList"></showData>
    </el-dialog>
    <!-- 筛选侧边栏 -->
    <el-drawer
      title="筛选数据项"
      :visible.sync="dialogLeft"
      direction="ltr"
      custom-class="demo-drawer"
      size="20%"
    >
      <screenList
        ref="screenList"
        @sendScreenMessage="getScreenList"
        @sendKeepList="getKeepList"
      ></screenList>
    </el-drawer>
  </div>
</template>
<script>
import { getAllStaff } from '@/api/organization'
import SearchCriteria from '../components/searchCriteria.vue'
import { getAllWeUser } from '@/api/customer/customerManage'
import { jobExtends, queryTaskList } from '@/api/customerInherit/jobInherit'
import showData from '../components/showData.vue'
import screenList from '../components/screenList.vue'

export default {
  name: 'jobInherit',
  components: {
    SearchCriteria,
    showData,
    screenList
  },
  data() {
    return {
      memberOption: [],
      customerList: '',
      customerNumber: '1',
      message: {
        sid: '',
        name: '', // 客户名称
        telphone: '',
        minAge: '',
        maxAge: '',
        gender: '',
        organization: '',
        channel: '',
        mode: '',
        follower: '',
        state: '',
        stage: '',
        pageNum: 1,
        pageSize: 10
      },
      // 下拉列表选项
      genderOptions: [],
      organizationList: [],
      modeList: [],
      followerList: [], //跟进人列表
      stateList: [
        { label: '是', value: '1' },
        { label: '否', value: '2' }
      ],
      stageOptions: [],
      remark: '客户转派',
      modifyForm: {
        reassign: '',
        platform: ''
      },
      saveLoading: false,
      modifyVisible: false,
      dialogFormVisible: false,
      tableSelectList: [],
      bussinessOption: [
        {
          value: '0',
          label: '创新'
        },
        {
          value: '1',
          label: '个险'
        },
        {
          value: '2',
          label: '银保'
        }
      ],
      platformOption: [],
      sourceOption: [],
      value: '',
      total: 0,
      loading: false,
      tableList: [],
      tableLists: [],
      query: {
        source: '',
        platform: '',
        line: '',
        createList: [], // 创建人
        pageNum: 1,
        pageSize: 20
      },
      ruleList: [], // 任务名称
      rules: {
        reassign: [
          { required: true, message: '请选择转派员工', trigger: 'change' }
        ]
      },
      staffList: [], // 所有员工列表
      rowContent: null, // 选中行信息
      // 侧边筛选
      dialogLeft: false,
      messages: {
        pageNum: 1,
        pageSize: 20
      },
      dictOptions: [
        { dict: 'follow_states', list: [], label: 'followStage' },
        { dict: 'marital', list: [], label: 'marital' },
        { dict: 'education', list: [], label: 'education' },
        { dict: 'job_type', list: [], label: 'job' },
        { dict: 'nationality', list: [], label: 'nationality' },
        { dict: 'friend_status', list: [], label: 'friendStatus' },
        { dict: 'customer_grade', list: [], label: 'customerGrade' },
        { dict: 'is_bind_wechat', list: [], label: 'isBindWechat' },
        { dict: 'distribution_state', list: [], label: 'distributionState' },
        { dict: 'wecom_add_state', list: [], label: 'wecomAddState' },
        { dict: 'state', list: [], label: 'state' }
      ]
    }
  },
  created() {
    // 性别
    this.getDicts('sys_user_sex').then((res) => {
      if (res.code === 200) {
        this.genderOptions = res.data
      }
    })
    // 跟进阶段
    this.getDicts('sys_customer_trackState').then((res) => {
      if (res.code === 200) {
        this.stageOptions = res.data
      }
    })
    this.getDictOptions()
    // 获取跟进人列表
    const params = {
      department: '',
      userName: ''
    }
    getAllWeUser(params)
      .then((res) => {
        if (res.code === 200) {
          this.followerList = res.data
        }
      })
      .catch(() => {
        console.log('error submit!!')
      })
    // this.queryTaskList();
    this.getAllStaff()
  },
  mounted() {
    this.$refs.child.search()
    this.getDataList()
  },
  methods: {
    handleSizeChange(val) {
      this.messages.pageNum = 1;
      this.messages.pageSize = val;
      this.getList()
    },
    handleCurrentChange(val) {
      this.messages.pageNum = val;
      this.getList()
    },
    // 年龄输入框限制
    minAge() {
      if (!/^[0-9]+$/.test(this.message.minAge)) {
        this.message.minAge = this.message.minAge.replace(/\D/g, '')
      }
      if (this.message.minAge > 100) this.message.minAge = 100
      if (this.message.minAge < 0) this.message.minAge = null
    },
    maxAge() {
      if (!/^[0-9]+$/.test(this.message.maxAge)) {
        this.message.maxAge = this.message.maxAge.replace(/\D/g, '')
      }
      if (this.message.maxAge > 100) this.message.maxAge = 100
      if (this.message.maxAge < 0) this.message.maxAge = null
    },
    testAge() {
      if (Number(this.message.minAge) > Number(this.message.maxAge)) {
        this.message.maxAge = null
        this.$message.error('最大年龄不得小于最小年龄')
      }
    },
    // 远程搜索任务名称 + 搜索
    queryTaskList(params) {
      this.loading = true
      params.pageType = '3'
      queryTaskList(params)
        .then((res) => {
          this.loading = false
          console.log(res, '------------表格res')
          if (res.rows.length === 0) {
            this.$message.success('查询数据为空')
          }
          if (res.code === 200 && res.rows.length) {
            res.rows.forEach((element) => {
              element.followStage = this.selectDictLabel(
                this.stageOptions,
                element.followStage - 1
              )
              this.dictOptions.forEach((item) => {
                element[item.label] = this.selectDictLabel(
                  item.list,
                  element[item.label]
                )
              })
            })
            this.tableList = res.rows
            this.total = res.total
            console.log(this.tableList, '-----------------this.tableList')
          } else {
            this.total = 0
            this.tableList = []
          }
        })
        .catch(() => {
          console.log('error')
          this.loading = false
        })
    },

    // 重置
    resetQuery() {
      this.message.sid = ''
      this.message.name = ''
      this.message.minAge = ''
      this.message.maxAge = ''
      this.message.gender = ''
      this.message.organization = ''
      this.message.channel = ''
      this.message.mode = ''
      this.message.follower = ''
      this.message.state = ''
      this.message.stage = ''
      this.message.pageNum = 1
      this.message.pageSize = 20
      this.message.createList = []
      this.queryTaskList()
    },

    getList() {
      this.$refs.child.search()
    },

    // 侧边栏筛选
    openDialogLeft() {
      this.dialogLeft = true
    },
    closeDialogLeft() {
      this.dialogLeft = false
    },
    getKeepList() {
      // 接收侧边栏保存
      this.closeDialogLeft()
      this.$refs.child.getLabelList()
    },
    // 接收侧边筛选
    getScreenList(value) {
      const params = {
        ...this.messages,
        pageType: '5',
        ...value
      }
      this.queryTaskList(params)
    },
    getMessage(value) {
      const params = {
        ...this.messages,
        pageType: '1',
        ...value
      }
      this.queryTaskList(params)
    },

    // 表格勾选事件
    handleSelectionChange(value) {
      this.tableSelectList = value
    },

    // 改变业务条线
    changeLine() {
      console.log(this.bussinessOption)
      console.log(this.query.line)
    },

    // 在职继承
    inherit(row) {
      this.customerList = row.name
      this.rowContent = row
      this.modifyVisible = true
      this.modifyForm.reassign = ''
      this.modifyForm.platform = ''
      this.$nextTick(() => {
        this.$refs.modifyForm.clearValidate()
      })
    },

    // 获取转派员工
    getAllStaff() {
      getAllStaff().then(({ data }) => {
        this.staffList = Object.freeze(data)
      })
    },

    saveModify() {
      this.$refs.modifyForm.validate((valid) => {
        if (valid) {
          const params = {
            externalUserid: this.rowContent.externalUserid,
            handoverUserid: this.rowContent.firstUserId,
            takeoverUserid: this.modifyForm.reassign,
            copywriter: this.modifyForm.text,
            sid: this.rowContent.sid
          }
          if (this.rowContent.sysUserId) {
            params.sysUserId = Number(this.rowContent.sysUserId)
          }
          this.saveLoading = true
          jobExtends(params)
            .then((res) => {
              console.log(res, '----------------res继承')
              this.saveLoading = false
              if (res.code === 200) {
                this.$message.success('在职继承成功!')
                this.modifyVisible = false
                const params = {
                  pageNum: 1,
                  pageSize: 20
                }
                this.queryTaskList(params)
              } else {
                this.$message.error(res.msg)
                this.modifyVisible = false
              }
            })
            .catch((err) => {
              this.saveLoading = false
            })
        }
      })
    },

    // 字典封装方法
    getDictOptions() {
      this.dictOptions.forEach((item) => {
        this.getDicts(item.dict).then((res) => {
          if (res.code === 200) {
            item.list = res.data
          }
        })
      })
    },

    // 展示数据项
    openShowList() {
      this.dialogFormVisible = true
      setTimeout(() => {
        this.$refs.showDataList.getLabelList()
      }, 100)
    },

    getDataList(value) {
      // 接收展示数据项
      this.dialogFormVisible = false
      console.log(
        JSON.parse(sessionStorage.getItem('siftList')),
        '---------siftList'
      )
      const siftList = JSON.parse(sessionStorage.getItem('siftList'))
      if (siftList) {
        this.tableLists = siftList
        // 在数据更新后执行
        this.$nextTick(() => {
          if (this.$refs.mainTable && this.$refs.mainTable.doLayout) {
            this.$refs.mainTable.doLayout()
          }
        })
      }
    },

    cancelModify() {
      this.modifyVisible = false
      this.$refs.modifyForm.resetFields()
    }
  }
}
</script>


<style lang="scss" scoped>
@import "../../../styles/base.scss";

.search {
  display: flex;
  padding: 10px 20px 10px;
  flex-wrap: wrap;
  justify-content: space-between;

  .demo-input {
    width: 22%;
    display: flex;
    align-items: center;
    margin: 5px 30px 10px 0;

    .el-input {
      margin-left: 20px;
      flex: 1;
    }

    span {
      margin-left: 20px;
    }

    .el-select {
      width: 100%;
      flex: 1;
      margin-left: 20px;
    }
  }
}

.wecomAdd1 {
  color: #666666;
}

.wecomAdd2 {
  color: #082aff;
}

.wecomAdd3 {
  color: #cccccc;
}

.header-search-select {
  margin-left: 15px;
}

::v-deep .el-table th.el-table__cell.is-leaf,
.el-table td.el-table__cell {
  border-bottom: none !important;
}

::v-deep .el-table .el-table__header-wrapper th {
  background-color: #f8f8f9 !important;
}

::v-deep {
  .demo-drawer {
    top: 60px;
  }
}
</style>
